package com.carl.web.servlet;

import com.alibaba.fastjson.JSON;
import com.carl.pojo.User;
import com.carl.service.UserService;
import com.carl.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
//    private UserService userService = new UserServiceImplx();
    private UserService userService = new UserServiceImpl();

    public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        System.out.println("user add ");
//        User user = new User();
//        user.setUsername("zhangsan");
//        user.setPassword("1234");
//
//        String s = JSON.toJSONString(user);
//        System.out.println(s);
//        JSON.parseObject("",User.class);

        BufferedReader reader = req.getReader();
        String params = reader.readLine();
        System.out.println(params);
        User user = JSON.parseObject(params, User.class);
        System.out.println(user);
        User u = userService.selectByUsername(user.getUsername());
        if (u == null) {
            userService.add(user);
            resp.getWriter().write("success");
        }else {
            resp.getWriter().write("false");
        }


    }

    public void selectByUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        BufferedReader reader = req.getReader();
        String params = reader.readLine();
        System.out.println(params);
        User user = JSON.parseObject(params, User.class);
        System.out.println(user);
        User u = userService.selectByUsername(user.getUsername());
        if (user.getPassword().equals(u.getPassword())) {
            System.out.println("验证成功");
            // 如果验证成功，则转发succeed.jsp页面，并在页面显示用户名
            if("zhangsan".equals(user.getUsername())){
                resp.getWriter().write("admin");
            }else {
                resp.getWriter().write("success");
            }


        } else {
            resp.getWriter().write("false");
        }

    }


}
